<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use fast\Random;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Access extends Backend
{

    /**
     * Dispatch
     * @var \app\admin\model\Dispatch
     */
    protected $noNeedLogin = ['test'];
    protected $model = null;
    protected $fiveindustryArr = [];
    protected $streetArr = [];
    protected $industryCategoryArr = [];
    protected $tablename = 'access';
    protected $year;
    protected $chargedep_data = null;
    protected $pre = '';
    protected $project_socialized = [];
    public function _initialize()
    {
        parent::_initialize();

       
        $this->model = new \app\admin\model\Access;

        $this->progress_model = new \app\admin\model\Progress;
        $this->chargedep_model = new \app\admin\model\Chargedep;

        // 项目状态
        $progress_list = $this->progress_model->select();
        $this->assign('progress_list',$progress_list);

        // 负责部门
        $chargedep_list = $this->chargedep_model->select();
        $this->assign('chargedep_list',$chargedep_list);

        $this->whereExtend['is_delete'] = 0;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);


        // pr($this->model);
        // exit();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($this->whereExtend)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($this->whereExtend)
                ->order($this->sortExtend)
                ->limit($offset, $limit)
                ->select();
            // echo $this->model->getLastSql();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();

    }
    public function add(){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $exist_row = $this->model->where(['name'=>$params['name'],'is_delete'=>0])->find();
                if($exist_row)
                    $this->error(__("此项目{$exist_row['name']}已存在"));
                
                if (isset($params['settle_street_ids'])) {
                    $row_info = $this->chargedep_model->get($params['settle_street_ids']);
                    $accompany_name = $row_info->name;
                    $params['settle_street_names'] = $accompany_name;
                    $params['chargedep_ids'] = $params['settle_street_ids'];
                    $params['chargedep_names'] = $accompany_name;
                }
                // if (isset($params['status'])) {
                //     $info = $this->progress_model->get($params['status']);
                //     $params['status_name'] = $info->name;
                // }
                if(isset($params['land_time']))
                {
                    if($params['land_time']=='待定')
                    {
                        $params['land_time_desc'] = $params['land_time'];
                        $params['land_time'] = 0; 
                    }else
                        $params['land_time_desc'] = "";
                }
                $params['pno'] = Random::uuid();


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();

    }
    public function edit($ids = NULL) {
        $row = $this->model->get($ids);
        if (!$row) {
            exit($ids);
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if (isset($params['settle_street_ids'])) {
                    $row_info = $this->chargedep_model->get($params['settle_street_ids']);
                    $accompany_name = $row_info->name;
                    $params['settle_street_names'] = $accompany_name;
                    $params['chargedep_ids'] = $params['settle_street_ids'];
                    $params['chargedep_names'] = $accompany_name;
                }
                // if (isset($params['status'])) {
                //     $info = $this->progress_model->get($params['status']);
                //     $params['status_name'] = $info->name;
                // }
                if(isset($params['land_time']))
                {
                    if($params['land_time']=='待定')
                    {
                        $params['land_time_desc'] = $params['land_time'];
                        $params['land_time'] = 0; 
                    }else
                        $params['land_time_desc'] = "";
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    
    public function detail($ids = null){
        if(!$ids){
            $this -> error('请刷新重试');
        }

        $row = $this -> model -> find($ids);

        $this -> assign('row',$row);
        return $this -> fetch();
    }

    /*
     *  删除，更改状态  
     */
    public function del($ids = null ){
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> model -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->is_delete = 1;
        $row->save();
        $this->success();
    }
    //
    public function export(){
        ini_set('memory_limit', '999M');

        $xlsName = '准入例会上会数据导出';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model->with($this->relationtTable)
            ->where($where)
            ->where($this->whereExtend)
            ->select();

        $xlsCell = array('序号','项目名称','投资方','总投资(亿元)','占地面积(亩)','项目简介','参加准入例会时间','(预计)拿地时间','进展情况','存在问题','下步措施','责任单位','备注');
        foreach ($list as $key => $value) {

            if($value['land_time']>0){
                $land_time_desc = $value['land_time_text'];
            }else if(isset($value['land_time_desc'])){
                $land_time_desc = $value['land_time_desc'];
            }
            $xlsDataReal[] = [
                ++$key,
                $value['name'],
                $value['investment_name'],
                $value['investment_total'],
                $value['carrier_area'],
                $value['summary'],
                $value['join_access_time_text'],
                $land_time_desc,
                $value['status_name'],
                $value['exist_question'],
                $value['explain'],
                $value['chargedep_names'],
                $value['remarks'],
            ];
        }
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);
    }


}
